// 先来自己写写链表的实现代码，不会的地方先想一会不会再去看
function LinkedList(head, length) {
    function Node(data) {
        this.data = data;
        this.next = null;
    }
    this.head = null;
    this.length = 0;

    // 1. append 在链表的末尾插入一个新节点
    LinkedList.prototype.append = function (data) {
        let newNode = new Node(data);
        // 先判断链表长度是否为 0
        if (this.length == 0) {
            this.head = newNode;
        } else {
            let current = this.head;
            while (current.next) {
                current = current.next;
            }
            current.next = newNode;
        }
    }

    // 2. insert 在链表的任意位置插入节点
    LinkedList.prototype.insert = function (position, data) {
        let newNode = new Node(data);
        // 看到有 position 先要判断越界条件
        if (position < 0 || position > this.length) return false;
        let index = 0;
        let current = this.head;
        let previous = null;
        while (index++ < position) {
            previous = current;
            current = current.next;
        }
        previous.next = newNode;
        newNode.next = current;
        length += 1;
    }
}

// 测试代码
let list = new LinkedList();
list.append('g');
list.append('r');
list.append('e');
list.append('n');
console.log(list);

list.insert(4, 'x');
console.log(list);
